﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using EkStudio.com.bean.xml.RootInterface.Field;
using EkStudio.com.bean.xml.ProjectMenu;
using EkStudio.com.bean.xml.RootInterface.Plugin;
using ScintillaNET;
using System.Drawing;
using EkStudio.Com.UI.Interface;
using EkStudio.com.bean.xml.Unit;
using EkStudio.com.common.unit;
using EkStudio.com.bean.xml.BillMultiple;
using EkStudio.com.bean.xml.reflection.JAXB;
using System.Text;
using EkStudio.com.bean.xml.RootInterface;

namespace EkStudio.com.ui.form
{
    public partial class FieldItemLinkerForm : XtraForm
    {
        private BillFormatModule format = null;
        private BillUiFieldsItem field = null;
        private ProjectRootPanel RootPanel = null;
        private BillExpandCodeRoot Expand = null;
        private ProjectUnitBillInterface ParentPanel = null;
        private string fixedFunction = "";
        public FieldItemLinkerForm(BillFormatModule _format,BillUiFieldsItem _field,ProjectRootPanel root,BillExpandCodeRoot expand, ProjectUnitBillInterface panel)
        {
            InitializeComponent();
            format = _format;
            field = _field;
            RootPanel = root;
            Expand = expand;
            ParentPanel = panel;
            initForm();
        }

        private void initForm()
        {

            #region 初始编辑器
            this.JScriptMemo.Margins[0].Width = 20;
            this.JScriptMemo.Margins[2].Type = MarginType.Symbol;
            this.JScriptMemo.Margins[2].Mask = Marker.MaskFolders;
            this.JScriptMemo.Margins[2].Sensitive = true;
            this.JScriptMemo.Margins[2].Width = 20;

            JScriptMemo.Markers[Marker.Folder].Symbol = MarkerSymbol.BoxPlus;
            JScriptMemo.Markers[Marker.FolderOpen].Symbol = MarkerSymbol.BoxMinus;
            JScriptMemo.Markers[Marker.FolderEnd].Symbol = MarkerSymbol.BoxPlusConnected;
            JScriptMemo.Markers[Marker.FolderMidTail].Symbol = MarkerSymbol.TCorner;
            JScriptMemo.Markers[Marker.FolderOpenMid].Symbol = MarkerSymbol.BoxMinusConnected;
            JScriptMemo.Markers[Marker.FolderSub].Symbol = MarkerSymbol.VLine;
            JScriptMemo.Markers[Marker.FolderTail].Symbol = MarkerSymbol.LCorner;

            JScriptMemo.StyleResetDefault();
            JScriptMemo.Styles[Style.Default].Font = "Consolas";
            JScriptMemo.Styles[Style.Default].Size = 10;
            JScriptMemo.StyleClearAll();


            // Configure the CPP (C#) lexer styles
            JScriptMemo.Styles[Style.Cpp.Default].ForeColor = Color.Silver;
            JScriptMemo.Styles[Style.Cpp.Comment].ForeColor = Color.FromArgb(0, 128, 0); // Green
            JScriptMemo.Styles[Style.Cpp.CommentLine].ForeColor = Color.FromArgb(0, 128, 0); // Green
            JScriptMemo.Styles[Style.Cpp.CommentLineDoc].ForeColor = Color.FromArgb(128, 128, 128); // Gray
            JScriptMemo.Styles[Style.Cpp.Number].ForeColor = Color.Olive;
            JScriptMemo.Styles[Style.Cpp.Word].ForeColor = Color.Blue;
            JScriptMemo.Styles[Style.Cpp.Word2].ForeColor = Color.Blue;
            JScriptMemo.Styles[Style.Cpp.String].ForeColor = Color.FromArgb(163, 21, 21); // Red
            JScriptMemo.Styles[Style.Cpp.Character].ForeColor = Color.FromArgb(163, 21, 21); // Red
            JScriptMemo.Styles[Style.Cpp.Verbatim].ForeColor = Color.FromArgb(163, 21, 21); // Red
            JScriptMemo.Styles[Style.Cpp.StringEol].BackColor = Color.Pink;
            JScriptMemo.Styles[Style.Cpp.Operator].ForeColor = Color.Purple;
            JScriptMemo.Styles[Style.Cpp.Preprocessor].ForeColor = Color.Maroon;
            JScriptMemo.Lexer = Lexer.Cpp;

            // Set the keywords
            JScriptMemo.SetKeywords(0, "function abstract as base break case catch checked continue default delegate do else event explicit extern false finally fixed for foreach goto if implicit in interface internal is lock namespace new null object operator out override params private protected public readonly ref return sealed sizeof stackalloc switch this throw true try typeof unchecked unsafe import virtual while");
            JScriptMemo.SetKeywords(1, "boolean var byte char class const decimal double enum float int long sbyte short static string struct uint ulong ushort void");

            
            JScriptMemo.Enabled = !ParentPanel.ReadOnly;

            #endregion


            MulComboBoxList.Properties.Items.Clear();
            fixedFunction = string.Format("{0}_linker", field.Key);

            //初始多样式表单
            if (RootPanel.MenuItem.MultipleProperties != null&&RootPanel.MenuItem.MultipleProperties.MultipleProperties!=null
                &&RootPanel.MenuItem.MultipleProperties.MultipleProperties.Count>0)
            {
                int selectIndex = -1;
                List<ProjectMenuCommonElement> list = RootPanel.MenuItem.MultipleProperties.MultipleProperties;
                for(int i = 0; i < list.Count; i++)
                {
                    ProjectMenuCommonElement it = list[i];
                    MulComboBoxList.Properties.Items.Add(it.Caption);
                    if (field != null && field.ViewBorder != null && field.ViewBorder.Linker != null)
                    {
                        if(it.Caption == field.ViewBorder.Linker.Caption)
                        {
                            selectIndex = i;
                        }
                    }
                }
                MulComboBoxList.SelectedIndex = selectIndex;
            }
            //初始参数脚本函数对象
            if (Expand != null && Expand.Jscript != null && Expand.Jscript.Item != null && Expand.Jscript.Item.Count > 0)
            {
                List<BillExpandJsCodeItem> list = Expand.Jscript.Item;

                for(int i = 0; i < list.Count; i++)
                {
                    BillExpandJsCodeItem it = list[i];
                    if (field != null && field.ViewBorder != null && field.ViewBorder.Linker != null)
                    {
                        if (it.Key == field.ViewBorder.Linker.DisposeJscript)
                        {
                            JScriptMemo.Text = it.Content;
                        }
                    }
                }
            }

        }

        private void BtnSubmit_Click(object sender, EventArgs e)
        {
            if (field != null)
            {
                //验证
                string caption = (string)MulComboBoxList.SelectedItem;
                if (caption == "")
                {
                    ErrorLab_one.Visible = true;
                }
                else
                {
                    if (field.ViewBorder.Linker == null) field.ViewBorder.Linker = new BillUiFieldsViewBorderLinker();
                    //获取资料
                    if (RootPanel.MenuItem.MultipleProperties != null && RootPanel.MenuItem.MultipleProperties.MultipleProperties != null)
                    {
                        List<ProjectMenuCommonElement> list = RootPanel.MenuItem.MultipleProperties.MultipleProperties;
                        for (int i = 0; i < list.Count; i++)
                        {
                            ProjectMenuCommonElement it = list[i];
                            if (it.Caption == (string)MulComboBoxList.SelectedItem)
                            {
                                field.ViewBorder.Linker.Caption = it.Caption;
                                field.ViewBorder.Linker.Key = it.Command;
                                field.ViewBorder.Linker.LanguageTexts = it.LanguageTexts;
                                field.ViewBorder.Linker.ShInWindow = false;
                                break;
                            }
                        }
                    }
                    field.ViewBorder.Linker.DisposeJscript = fixedFunction;
                    //查找当前js列表中是否存在此同名函数
                    if (Expand.Jscript == null) Expand.Jscript = new BillExpandJsCodeRoot();
                    if (Expand.Jscript.Item == null) Expand.Jscript.Item = new List<BillExpandJsCodeItem>();
                    BillExpandJsCodeItem jscript = null;
                    if (Expand.Jscript.Item.Count > 0)
                    {
                        foreach(BillExpandJsCodeItem js in Expand.Jscript.Item)
                        {
                            if(js.Key == fixedFunction)
                            {
                                jscript = js;
                                break;
                            }
                        }
                    }
                    if (jscript == null)
                    {
                        jscript = new BillExpandJsCodeItem();
                        Expand.Jscript.addNode(jscript, format);
                    }
                    jscript.Key = fixedFunction;
                    jscript.Caption = string.Format("{0}的链接", field.Caption);
                    jscript.Content = JScriptMemo.Text;
                    jscript.PluginType = BeanUtil.JSCRIPT_FORM_TYPE[1];//查询界面js
                    
                    
                    DialogResult = DialogResult.OK;
                    this.Close();
                }
                
                
            }
        }

        private void MulComboBoxList_MouseClick(object sender, MouseEventArgs e)
        {
            ErrorLab_one.Visible = false;
        }

        private void JsComboBoxList_MouseClick(object sender, MouseEventArgs e)
        {
            ErrorLab_one.Visible = false;
        }

        private void BtnAutoJScript_Click(object sender, EventArgs e)
        {
            if (JScriptMemo.Text != "")
            {
                if(XtraMessageBox.Show("您确认替换原有的脚本吗?","警告", MessageBoxButtons.YesNo,MessageBoxIcon.Question) != DialogResult.Yes)
                {
                    return;
                }
            }
            //加载多样式表单
            String Caption = (string)MulComboBoxList.SelectedItem;
            ProjectMenuCommonElement check = null;
            //获取资料
            if (RootPanel.MenuItem.MultipleProperties != null && RootPanel.MenuItem.MultipleProperties.MultipleProperties != null)
            {
                List<ProjectMenuCommonElement> list = RootPanel.MenuItem.MultipleProperties.MultipleProperties;
                
                for (int i = 0; i < list.Count; i++)
                {
                    ProjectMenuCommonElement it = list[i];
                    if (it.Caption == Caption)
                    {
                        check = it;
                        break;
                    }
                }
            }
            if(check==null)
            {
                RootPanel.AddConsoleText(string.Format("表单[{0}]不存在", Caption), true);
                return;
            }
            bool red = false;
            Dictionary<string, string> pm = new Dictionary<string, string>();
            pm.Add("validation", "false");
            String xml = RootPanel.Http.ResourcesXmlBean(check.Command, check.Caption, ProjectUtil.TYPE_BILL_MULTIPLE,ref red, pm);
            BillMultipleItem bean = null;
            JAXBContext<BillMultipleItem> jaxb = new JAXBContext<BillMultipleItem>();
            bool success = true;
            try
            {
                bean = jaxb.unmarshal(xml);
            }
            catch
            {
                RootPanel.AddConsoleText("打开多样式表单失败", true);
                success = false;
            }
            if (success && bean != null)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("function ").Append(fixedFunction).Append("(tr){").AppendLine();
                sb.Append("    //请不要擅自修改函数名\n");
                sb.Append("    var record_id_value = $('input[name=record_id]',tr).val();\n");

                StringBuilder p = new StringBuilder();
                if (bean.ParamProperties!=null&&bean.ParamProperties.ParamItem!=null
                    && bean.ParamProperties.ParamItem.Count > 0)
                {
                    foreach(BillMultipleParamItem param in bean.ParamProperties.ParamItem)
                    {
                        sb.Append("    //传递参数[").Append(param.Caption).Append("]的值\n");
                        sb.Append("    var ").Append(param.Key).Append("_value = \"\";\n");
                        sb.Append("    var ").Append(param.Key).Append("_jquery = $('td[abbr=").Append(param.Key).Append("] > div',tr);\n");
                        sb.Append("    if(").Append(param.Key).Append("_jquery.length>0){").Append(param.Key);
                        sb.Append("_value = ").Append(param.Key).Append("_jquery.text();}\n");
                        p.Append(",").Append(param.Key).Append(":").Append(param.Key).Append("_value");
                    } 
                }
                sb.Append("    return {record_id:record_id_value").Append(p).Append(",showInWin:false};\n");
                sb.Append("}");
                JScriptMemo.Text = sb.ToString();
            }
        }
    }
}